﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Globalization;
using bdnt_pets_system.Resources;
using System.Windows.Data;
using bdnt_pets_system.Tools;
using bdnt_pets_system_Entity;
using bdnt_pets_system.SystemServiceReference;

namespace bdnt_pets_system.PageViews.SystemViews
{
    public partial class NewRoleControl : BaseUserControl
    {
        SystemServiceReference.SystemServiceClient sysClient;

        public Tbl_Role CuTbl_Role
        {
            get { return this.DataContext as Tbl_Role; }
            set { this.DataContext = value; }
        }
        public NewRoleControl(Int32 rolId = 0)
        {
            InitializeComponent();
            BingData();
            sysClient = new SystemServiceReference.SystemServiceClient();
            InitEvnet();
            if (rolId == 0)
            {
                CuTbl_Role = new Tbl_Role() { RoleState = 1 };
                LoadData();
            }
            else
                sysClient.GetRoleObjByIdAsync(rolId);
        }

        void InitEvnet()
        {
            btnCancel.Click += new RoutedEventHandler(btnCancel_Click);
            btnOk.Click += new RoutedEventHandler(btnOk_Click);
            sysClient.SaveRoleObjCompleted += new EventHandler<SaveRoleObjCompletedEventArgs>(sysClient_SaveRoleObjCompleted);
            sysClient.GetRoleObjByIdCompleted += new EventHandler<GetRoleObjByIdCompletedEventArgs>(sysClient_GetRoleObjByIdCompleted);
        }

        void sysClient_GetRoleObjByIdCompleted(object sender, GetRoleObjByIdCompletedEventArgs e)
        {
            CuTbl_Role = e.Result;
            LoadData();
        }
        //绑定数据
        void BingData()
        {
            tbMc.SetBinding(TextBox.TextProperty, new Binding("RoleName")
            {
                Mode = BindingMode.TwoWay,
                NotifyOnValidationError = true,
                ValidatesOnExceptions = true
            });
            tbSm.SetBinding(TextBox.TextProperty, new Binding("Remark") { Mode = BindingMode.TwoWay });
        }

        void LoadData()
        {
            if (CuTbl_Role.RoleState == 1)
                rbZc.IsChecked = true;
            else
                rbGb.IsChecked = true;
            InitMenus();

        }

        void sysClient_SaveRoleObjCompleted(object sender, SaveRoleObjCompletedEventArgs e)
        {
            if (e.Result)
            {
                App.ToPage(new RoleManagerControl());
            }
            else
            {
                errorMsg.SetBinding(TextBlock.TextProperty, new Binding("Strings.bcsb") { Source = CuLc });
            }
        }

        void btnOk_Click(object sender, RoutedEventArgs e)
        {
            tbMc.GetBindingExpression(TextBox.TextProperty).UpdateSource();
            if (vs.Errors.Count() > 0)
            {
                errorMsg.Text = MyStrings.sjtxbq;// "数据填写不全！";
                return;
            }

            if (rbZc.IsChecked == true)
                CuTbl_Role.RoleState = 1;
            else CuTbl_Role.RoleState = 0;

            ObservableCollection<int> menuIds = new ObservableCollection<int>();
            foreach (var item in tvMenu.Items)
            {
                GetMenuIds(item as TreeViewItem, ref menuIds);
            }
            sysClient.SaveRoleObjAsync(CuTbl_Role, menuIds);
        }

        void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            App.ToPage(new RoleManagerControl());
        }

        public void GetMenuIds(TreeViewItem itm, ref ObservableCollection<int> menuIds)
        {
            var cuC = itm.Tag as CheckBox;
            if (cuC.IsChecked == true)
            {
                var cuM = (cuC.Tag as Tbl_Menu);
                menuIds.Add(cuM.Id);
            }
            foreach (var item in itm.Items)
            {
                GetMenuIds(item as TreeViewItem, ref menuIds);
            }
        }
        List<int> mIds = new List<int>();
        #region 权限菜单
        void InitMenus()
        {
            var allMenus = SessionManager.AllMenus;
            if (allMenus.Count == 0)
                return;
            mIds = !string.IsNullOrEmpty(CuTbl_Role.MeunIds) ? CuTbl_Role.MeunIds.Split(',').Select(p => Int32.Parse(p)).ToList()
                : mIds;

            tvMenu.Items.Clear();

            var pMs = allMenus.Where(p => p.PMenuId == 0).OrderBy(p => p.MenuSequence);
            foreach (var item in pMs)
            {
                TreeViewItem cuI = new TreeViewItem();
                CheckBox ck = new CheckBox();
                ck.Tag = item;
                if (mIds.Contains(item.Id))
                    ck.IsChecked = true;
                cuI.Tag = ck;

                ck.Content = SessionManager.IsCN_ZH ? item.MenuName : item.en_MenuName;

                cuI.Header = ck;
                cuI.DataContext = item;
                AddChildNode(cuI, item, allMenus);
                cuI.IsExpanded = true;
                tvMenu.Items.Add(cuI);
            }
        }

        void AddChildNode(TreeViewItem pitem, Tbl_Menu pmenu, ObservableCollection<Tbl_Menu> source)
        {
            var cuos = source.Where(c => c.PMenuId == pmenu.Id).OrderBy(p => p.MenuSequence);
            foreach (var item in cuos)
            {
                TreeViewItem cuI = new TreeViewItem();
                CheckBox ck = new CheckBox();
                ck.Tag = item;
                cuI.Tag = ck;

                if (mIds.Contains(item.Id))
                    ck.IsChecked = true;


                ck.Content = SessionManager.IsCN_ZH ? item.MenuName : item.en_MenuName;

                cuI.Header = ck;
                cuI.DataContext = item;
                AddChildNode(cuI, item, source);
                cuI.IsExpanded = true;
                pitem.Items.Add(cuI);
            }
        }
        #endregion
    }
}
